<?php
use WebSocket\Client;

class GameClient
{
    private $client;
    private $host;
    private $port;
    private $username;
    private $token;
    private $userInfo;

    public function __construct($host = 'localhost', $port = 2346)
    {
        $this->host = $host;
        $this->port = $port;
    }

    public function connect($token)
    {
        $this->token = $token;
        $this->client = new \WebSocket\Client("ws://{$this->host}:{$this->port}");
        
        // 连接后立即发送认证信息
        $this->authenticate();
    }

    private function authenticate()
    {
        $this->client->send(json_encode([
            'type' => 'authenticate',
            'token' => $this->token
        ]));
        
        $response = $this->client->receive();
        $data = json_decode($response, true);
        
        if ($data['type'] === 'authenticated') {
            $this->username = $data['username'];
            $this->userInfo = $data['userInfo'];
            return true;
        }
        
        $errorMsg = $data['message'] ?? '认证失败';
        $errorCode = $data['code'] ?? -1;
        throw new Exception($errorMsg, $errorCode);
    }

    private function addTokenToRequest($data)
    {
        return array_merge($data, ['token' => $this->token]);
    }

    public function createRoom()
    {
        $this->client->send(json_encode(
            $this->addTokenToRequest(['type' => 'createRoom'])
        ));
        return $this->client->receive();
    }

    public function joinRoom($roomId)
    {
        $this->client->send(json_encode(
            $this->addTokenToRequest([
                'type' => 'joinRoom',
                'roomId' => $roomId
            ])
        ));
        return $this->client->receive();
    }

    public function ready()
    {
        $this->client->send(json_encode(
            $this->addTokenToRequest(['type' => 'ready'])
        ));
        return $this->client->receive();
    }

    public function sendGameAction($action)
    {
        $this->client->send(json_encode(
            $this->addTokenToRequest([
                'type' => 'gameAction',
                'action' => $action
            ])
        ));
        return $this->client->receive();
    }

    public function close()
    {
        $this->client->close();
    }
} 